import { _decorator, Component, EditBox, instantiate, Node, Prefab, ScrollView, UITransform } from 'cc';

const { ccclass, property } = _decorator;

import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';

import { UIHeader } from '../common/UIHeader';
import { EventManager } from '../event/EventManager';
import { ChatItem } from '../AI/ChatItem';

@ccclass('NoticeList')
export class NoticeList extends Component {
    @property(UIHeader)
    uiHeader: UIHeader
    @property(ScrollView)
    scrollView: ScrollView
    @property(Node)
    content: Node
    @property(Node)
    empty:Node
    @property(Prefab)
    chatItem: Prefab

    msgList: any[]

    start() {
        this.uiHeader.setData(`世界动态`)
        EventManager.instance.on(`世界动态close`, this.onClose, this)

        EventManager.instance.on(EventManager.EventType.Notice, this.onNotice, this)
    }

    protected onDisable(): void {
        EventManager.instance.off(EventManager.EventType.Notice, this.onNotice, this)
    }

    setData(list: any[]) {
        this.msgList = list

        for (let msg of this.msgList) {
            this.send(`【${msg.fn}】${msg.msg}`)
        }

        this.scheduleOnce(() => {
            let scrollHeight = this.scrollView.getComponent(UITransform).height
            let contentHeight = this.content.getComponent(UITransform).height
            if (contentHeight >= scrollHeight) {
                this.scrollView.scrollToBottom()
            }
        }, 0.2)

    }

    onNotice(list: any[]) {
        this.msgList = this.msgList.concat(list)
        for (let msg of list) {
            this.send(`【${msg.fn}】${msg.msg}`)
        }
    }

    send(str: string) {
        let node = instantiate(this.chatItem)
        this.content.addChild(node)
        node.getComponent(ChatItem).setData(str)
        let scrollHeight = this.scrollView.getComponent(UITransform).height
        let contentHeight = this.content.getComponent(UITransform).height
        if (contentHeight >= scrollHeight) {
            this.scrollView.scrollToBottom()
        }


        this.empty.active = false
    }

    onClose() {
        UIManager.instance.closeUI(PrefabEnum.NoticeList)
    }
}


